// pages/goods/goods-order.js
var app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {

    goodsNum: 1,
    goodsTotal: 0,

    gsn: [],

    delivery: 1, //配送方式
    payment: 1, // 支付方式

    store_id: 0,

    record: 0, // 余额不足

    store_name: '点击选择门店：',

  },

  //配送方式
  bindDelivery(e) {
    var that = this;
    that.setData({
      delivery: e.currentTarget.dataset.id,
      store_id: 0,
      store_name: '点击选择门店：',
    })
  },

  //支付方式
  bindPayment(e) {
    var that = this;
    that.setData({
      payment: e.currentTarget.dataset.id
    })
  },

  bindstore(e) {
    this.setData({
      store_id: e.currentTarget.dataset.id
    })
  },

  bindnavTo(e) {
    var id = 1;
    this.setData({
      record: 0,
    })
    wx.navigateTo({
      url: '../my/my-core?card_id' + id
    })
  },

  bindstoreTo(e) {
    var that = this;
    var store_index = e.detail.value
    this.setData({
      store_index: store_index,
      store_id: that.data.ordersCar.store[store_index].id,
      store_name: that.data.ordersCar.store[store_index].name
    })
  },

  bindrecord(e) {
    this.setData({
      record: 0
    })
  },

  getallprices(e) {
    const that = this;
    var ordersCar = that.data.ordersCar;
    var goods = that.data.ordersCar.goods;
    var allprices = parseFloat(0);
    var gsn = [];
    for (var a = 0; a < goods.length; a++) {
      let num = parseInt(goods[a].num)
      let price = Number(goods[a].fee)
      allprices += price * num
    }
    for (var i = 0; i < goods.length; i++) {
      var arr = new Array(3)
      arr[0] = goods[i].id;
      arr[1] = goods[i].gs_id;
      arr[2] = goods[i].num;
      var array = arr.toLocaleString()
      gsn.push(array)
    }
    var str = allprices;
    that.setData({
      totalPrice: str.toFixed(2),
      gsn: gsn,
    })
  },

  bindMinus(e) {
    let that = this;
    var index = e.currentTarget.dataset.index
    var goods = that.data.goods[index];
    var num = Number(goods.num);
    if (num <= 1) {
      wx.showToast({
        title: '不能再减少了哦',
        duration: 500,
        icon: 'loading',
        mask: true,
        success: (res) => {},
      })
    } else {
      num -= 1;
      that.setData({
        ['goods[' + index + '].num']: num,
      })
      that.getallprices()
    }
  },

  bindPlus(e) {
    let that = this;
    var index = e.currentTarget.dataset.index
    var goods = that.data.goods[index];
    var num = Number(goods.num);
    var stock = Number(goods.stock);
    if (num >= stock) {
      wx.showToast({
        title: '库存不足',
        duration: 500,
        icon: 'loading',
        mask: true,
        success: (res) => {},
      })
    } else {
      num += 1;
      that.setData({
        ['goods[' + index + '].num']: num,
      })
      that.getallprices()
    }
  },


  orders_submit(e) {
    var that = this;
    var integral = that.data.delivery;
    var payment = that.data.payment;
    var integral = 1;
    wx.showLoading({
      title: '下单中',
      mask: true,
    })
    wx.request({
      url: app.globalData.url + 'Orders_submit',
      data: {
        uid: app.globalData.uid,
        store_id: that.data.store_id,
        fee: that.data.totalPrice,
        get_way: that.data.delivery,
        exfee: that.data.ordersCar.exefee,
        fee_way: that.data.payment,
        ad_id: that.data.add.id,
        gsn: that.data.gsn,
      },
      method: 'POST',
      success: function (res) {
        var oid = res.data.out_trade_no;
        var id = res.data.info;
        if (payment == 1) {
          wx.hideLoading()
          if (res.data.status == 1) {
            wx.showModal({
              cancelText: '想一想',
              confirmText: '确认',
              content: '确认使用余额支付',
              showCancel: true,
              success: (res) => {
                if (res.confirm == true) {
                  wx.request({
                    url: app.globalData.url + 'Payok',
                    data: {
                      oid: id,
                      car_id: that.options.selectId,
                    },
                    method: 'POST',
                    success: function (res) {
                      wx.navigateTo({
                        url: 'goods-orderInfo?oid=' + id + "&integral=" + integral,
                        success: function (res) {},
                      })
                    }
                  })
                }
              },
              title: '温馨提示',
            })
            return
          } else if (res.data.status == 3) {
            that.setData({
              record: 1
            })
            return
          }
        } else if (payment == 2) {
          wx.hideLoading()
          if (res.data.state == 1) {
            wx.requestPayment({
              timeStamp: res.data.timeStamp,
              nonceStr: res.data.nonceStr,
              package: res.data.package,
              signType: res.data.signType,
              paySign: res.data.paySign,
              fail: (res) => {
                wx.request({
                  url: app.globalData.url + 'Payfalse',
                  data: {
                    oid: oid,
                  },
                  method: 'POST',
                  success: function (res) {
                    if (res.data.info) {
                      wx.showToast({
                        title: '支付失败',
                        icon: "loading",
                        duration: 1200,
                        mask: true,
                      })
                    }
                  }
                })
              },
              success: (res) => {
                wx.request({
                  url: app.globalData.url + 'Payok',
                  data: {
                    oid: oid,
                    car_id: that.options.selectId,
                  },
                  method: 'POST',
                  success: function (res) {
                    wx.navigateTo({
                      url: 'goods-orderInfo?oid=' + oid + "&integral=" + integral,
                      success: function (res) {},
                    })
                  }
                })
              },
            })
          } else {
            wx.showToast({
              title: res.data.msg,
              icon: 'none',
              duration: 1200,
              mask: true,
            })
          }
        }
      },
    })
  },


  bindOrders_submit(e) {
    var that = this;
    var delivery = that.data.delivery;
    if (delivery == 1) {
      if (that.data.store_id == 0) {
        wx.showToast({
          title: '请选择门店地址',
          icon: "loading",
          duration: 1300,
          mask: true,
        })
        return
      } else {
        that.orders_submit()
      }
    } else if (delivery == 2) {
      if (that.data.store_id == 0) {
        wx.showToast({
          title: '请选择门店',
          icon: "loading",
          duration: 1300,
          mask: true,
        })
        return
      } else if (that.data.add.length == 0) {
        wx.showToast({
          title: '请添加收货地址',
          icon: "loading",
          duration: 1300,
          mask: true,
        })
        return
      } else {
        that.orders_submit()
      }
    }
  },

  navTo(e) {
    wx.navigateTo({
      url: e.currentTarget.dataset.url,
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.stopPullDownRefresh();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    const that = this;
    wx.showLoading({
      title: '玩命加载中',
      mask: true,
    })
    wx.request({
      url: app.globalData.url + 'OrdersPage',
      data: {
        gs_id: that.options.gs_id,
        gid: that.options.gid,
        car_id: that.options.selectId,
        uid: app.globalData.uid,
        ad_id: app.globalData.ad_id,
      },
      method: 'POST',
      success: function (res) {
        if (res.data.info) {
          if (res.data.info.addres != []) {
            app.globalData.ad_id = res.data.info.address.id;
          }
          that.setData({
            ordersCar: res.data.info,
            goods: res.data.info.goods,
            add: res.data.info.address,
          })
          that.getallprices()
        }
        wx.hideLoading()
      },
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.onLoad();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})